﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ZetaPrints.ZetaClient.Business;
using ZetaPrints.ZetaClient.Data.Repository.Linq;

namespace ZetaPrints.ZetaClient.Presentation
{
    /// <summary>
    /// The form for managing the sites
    /// </summary>
    public partial class FormSiteManagement : Form
    {
        #region public properties
        /// <summary>
        /// The list of sites as it is on FormSiteManager. This property
        /// will get manipulated as new entries are added or removed
        /// </summary>
        public List<Site> SiteList { get; set; }
        /// <summary>
        /// List of Sites which were removed during this dialog operation
        /// </summary>
        public List<Site> SiteDeleteList { get; set; }
        #endregion


        #region constructors
        public FormSiteManagement(List<Site> siteList)
        {
            InitializeComponent();

            SiteList = siteList;
            SiteDeleteList = new List<Site>();

            RefreshGrid();

            textBoxSiteName.TextChanged += new EventHandler(textBoxSiteName_TextChanged);

            AcceptButton = buttonOk;
            CancelButton = buttonCancel;

            textBoxSiteName.Leave += new EventHandler(textBoxSiteName_Leave);
        }       
        #endregion


        #region private methods
        private void RefreshGrid()
        {
            listViewSite.SuspendLayout();

            listViewSite.Items.Clear();

            foreach (Site site in SiteList)
            {
                List<string> fieldList = new List<string>();
                fieldList.Add(site.SiteId.ToString());
                fieldList.Add(site.SiteName);
                fieldList.Add(site.ApiKey.ToString());

                listViewSite.Items.Add(new ListViewItem(fieldList.ToArray()));
            }

            listViewSite.ResumeLayout();
        }
        /// <summary>
        /// Add the current site, will return true if the site was
        /// added or modify with no problems
        /// </summary>
        /// <returns></returns>
        private bool AddSite()
        {
            bool itemAdded = true;

            Guid apiKey = new Guid();
            /// get the site name and remove all the spaces before and after
            string siteName = textBoxSiteName.Text.Trim(' ');
            /// do checks first
            try
            {
                /// if we crash here we will fall into the 
                /// catch down there.
                apiKey = new Guid(textBoxApiKey.Text);

                if (siteName.Length > 0)
                {
                    if (siteName.Contains(" "))
                    {
                        MessageBox.Show(this, "Invalid character in site name, please check your site name and try again.", "Invalid Site Name", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        itemAdded = false;
                    }
                    else
                    {
                        /// entry was accepted. Go ahead and add/modify them.
                        bool siteModified = false;

                        for (int count = 0; count < SiteList.Count; count++)
                        {
                            if (siteName == SiteList[count].SiteName)
                            {
                                /// change only the api key
                                SiteList[count].ApiKey = apiKey;
                                siteModified = true;
                                break;
                            }
                        }

                        /// if the item was not already modified go ahead and add it in
                        if (!siteModified)
                        {
                            Site site = new Site();
                            site.SiteName = siteName;
                            site.ApiKey = apiKey;

                            SiteList.Add(site);
                        }

                        /// clear out the item we just added
                        textBoxSiteName.Text = string.Empty;
                        textBoxApiKey.Text = string.Empty;

                        RefreshGrid();
                    }
                }
                else
                {
                    MessageBox.Show(this, "No site name, please add a site name", "Invalid Site Name", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    itemAdded = false;
                }
            }
            catch
            {
                MessageBox.Show(this, "Invalid ApiKey format, it must be in GUID format.\n(ex. 18234857-1823-2834-2834-298394856784)",
                    "Invalid Guid", MessageBoxButtons.OK, MessageBoxIcon.Error);

                itemAdded = false;
            }

            return itemAdded;
        }
        #endregion


        #region event handlers
        #region cancel and ok
        private void buttonOk_Click(object sender, EventArgs e)
        {
            bool okToExit = true;

            /// if the textBoxSiteName is in place we need
            /// to try to add it before we leave
            if ((textBoxSiteName.Text.Length > 0))
            {
                /// if we unable to exit we must stop the exit
                /// procedure of this dialog
                if (!AddSite())
                {
                    okToExit = false;
                }
            }

            if (okToExit)
            {
                /// we need to do this to make sure we have not deleted an items
                /// and add the item back again. We do not want to delete the item
                /// from the database if that happened
                for (int count = 0; count < SiteDeleteList.Count; count++)
                {
                    foreach (Site siteItem in SiteList)
                    {
                        if (siteItem.SiteName == SiteDeleteList[count].SiteName)
                        {
                            SiteDeleteList.RemoveAt(count);
                            /// we want to do this item again, since
                            /// it was deleted
                            count--;
                            break;
                        }
                    }
                }

                DialogResult = DialogResult.OK;
                Close();
            }
        }
        /// <summary>
        /// When the button cancel is touched
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
        #endregion
        #region add modify button
        /// <summary>
        /// Adds the current entry record to the system
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            AddSite();
        }
        #endregion
        #region listview
        private void listViewSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            /// only do something if there is something selected
            if (listViewSite.SelectedItems.Count > 0)
            {
                textBoxSiteName.Text = (listViewSite.SelectedItems[0]).SubItems[1].Text;
                textBoxApiKey.Text = (listViewSite.SelectedItems[0]).SubItems[2].Text;
            }
        }
        #endregion
        #region delete button
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            string siteName = textBoxSiteName.Text;

            /// do we have anything selected?
            if (siteName.Length > 0)
            {
                int count = 0;

                for (; count < SiteList.Count; count++)
                {
                    if (siteName == SiteList[count].SiteName)
                    {
                        break;
                    }
                }

                if (SiteList.Count != count)
                {
                    switch (MessageBox.Show(this, "Deleting a site will delete ALL the order, order details, would you like to continue?", "Delete", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning))
                    {
                        case DialogResult.Yes:
                            SiteDeleteList.Add(SiteList[count]);
                            SiteList.RemoveAt(count);
                            /// empty out the selection
                            textBoxSiteName.Text = string.Empty;
                            textBoxApiKey.Text = string.Empty;
                            RefreshGrid();
                            break;
                    
                    }
                }
                else
                {
                    MessageBox.Show(this, "Item selected for delete does not exist to be delete, try again",
                        "Invalid item to delete", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show(this, "No item selected to be deleted, select an item from the grid and click delete again", 
                    "No item to delete", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion
        #region textBoxSiteName
        /// <summary>
        /// When we move out of the name area we want to make sure the 
        /// name is in the correct format
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void textBoxSiteName_Leave(object sender, EventArgs e)
        {
            string text = textBoxSiteName.Text.ToLower();

            /// remove the http:// header if one exits
            if (text.Contains("http://"))
            {
                text = text.Replace("http://", "");
            }

            textBoxSiteName.Text = text;
        }
        /// <summary>
        /// This will check if the name the text on the name
        /// was changed to something that is already on the list
        /// we want to change the text on the add button to modify
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void textBoxSiteName_TextChanged(object sender, EventArgs e)
        {
            bool modifyOn = false;

            foreach (Site site in SiteList)
            {
                if (site.SiteName == textBoxSiteName.Text)
                {
                    modifyOn = true;
                }
            }

            if (modifyOn)
            {
                buttonAdd.Text = "Modify";
            }
            else
            {
                buttonAdd.Text = "Add";
            }
        }
        #endregion        
        #endregion
    }
}
